<template>
  <div class="appEdit detailView">
    <div style="padding: 20px">
      <Row>
        <Col span="6">
        <Tree :data="treeData"
              :render="renderContent"
              class="demo-tree-render"></Tree>
        </Col>
        <Col span="18">
        <div ref="editor"
             class="editor">
          <el-form class="editorForm"
                   ref="contentData"
                   label-width="85px"
                   :model="contentData">
            <div ref="editor"
                 class="editor"
                 v-if="contentData != null">
              <el-form-item prop="content">
                标题： <Input type="text"
                       v-model="contentData.title" />
              </el-form-item>
              <el-form-item prop="content"
                            v-if="!modal11">
                <vue-neditor-wrap :destroy="true"
                                  v-model="contentData.content"
                                  style="z-index: 1;"
                                  :config="myConfig"></vue-neditor-wrap>
              </el-form-item>
            </div>
          </el-form>
        </div>
        </Col>
      </Row>
    </div>
    <div class="operationView">
      <Button type="primary"
              class="operation_btn"
              @click="handleCancel">取消</Button>
      <Button type="primary"
              class="operation_btn"
              @click="handleSave">保存</Button>
    </div>
    <Modal v-model="modal11"
           title="新增节点"
           @on-ok="asyncOK">
      <div><Input v-model="tempName"
               type="text" /></div>
    </Modal>
  </div>
</template>

<script>
  import Page from '@/base/page/page';
  import { mapGetters } from 'vuex';
  import VueNeditorWrap from 'vue-neditor-wrap';

  export default {
    name: "editDigitalProductView",
    data () {
      return {
        modal11: false,
        tempName: '',
        myConfig: {
          // 你的UEditor资源存放的路径,相对于打包后的index.html
          UEDITOR_HOME_URL: this.api.uEditorHomeUrl,
          // 编辑器不自动被内容撑高
          autoHeightEnabled: false,
          // 初始容器高度
          initialFrameHeight: '418',
          // 初始容器宽度
          initialFrameWidth: '100%',
          // 关闭自动保存
          enableAutoSave: false,
          scaleEnabled: true
        },
        currentData: {},
        uploadImgUrl: this.api.file.uploadImage,
        treeData:
          [
            {
              title: '数字产品',
              expand: true,
              selected: false,
              render: (h, { root, node, data }) => {
                let temp = data.title;
                if (temp.length > 20) {
                  temp = temp.substring(0, 18) + "...";
                }
                return h('span', {
                  style: {
                    display: 'inline-block',
                    width: '100%'
                  }
                }, [
                  h('span', {
                    style: {
                      cursor: 'pointer',
                    },
                    on: {
                      click: () => {
                        this.contentData = data;
                      }
                    }
                  }, [
                    h('Icon', {
                      props: {
                        type: 'ios-folder-outline'
                      },
                      style: {
                        marginRight: '8px'
                      }
                    }),
                    h('span', temp)
                  ]),
                  h('span', {
                    style: {
                      display: 'inline-block',
                      float: 'right',
                      marginRight: '32px'
                    }
                  }, [
                    h('Button', {
                      props: Object.assign({}, this.buttonProps, {
                        icon: 'ios-add',
                        type: 'primary'
                      }),
                      style: {
                        width: '64px'
                      },
                      on: {
                        click: () => {
                          this.append(data)
                        }
                      }
                    })
                  ])
                ]);
              },
              content: "",
              children: []
            }
          ],
        buttonProps: {
          type: 'default',
          size:
            'small',
        },
        contentData: null,
        rules: {
          name: [
            {
              required: true,
              message: '请输入名称',
              trigger: 'blur'
            }
          ]
        },
      }
    },
    mounted () {
      if (this.$route.query.id) {
        this._getDataById()
      }
    },
    created () {
    },
    methods: {
      _getDataById () {
        this.post(this.api.digitalProducts.getDigitalProduct, { id: this.$route.query.id }).then((res) => {
          if (res.data.code === '200') {
            let object = res.data.object;
            this.treeData[0].title = object.name;
            this.treeData[0].id = object.id;
            this.treeData[0].content = object.remark;
            let childrenContent = object.content;
            if (childrenContent) {
              let children = JSON.parse(childrenContent);
              if (!this.treeData[0].children) {
                this.treeData[0].children = [];
              }
              this.setChildrenData(children, this.treeData[0]);
            }
          }
        })
      },
      renderContent (h, { root, node, data }) {
        let temp = data.title;
        if (temp.length > 20) {
          temp = temp.substring(0, 18) + "...";
        }
        return h('span', {
          style: {
            display: 'inline-block',
            width: '100%'
          }
        }, [
          h('span', {
            style: {
              cursor: 'pointer',
            },
            on: {
              click: () => {
                this.contentData = data;
                if (data.expand) {
                  data.expand = false;
                } else {
                  data.expand = true;
                }
              }
            }
          },
            [
              h('Icon', {
                props: {
                  type: 'ios-paper-outline'
                },
                style: {
                  marginRight: '8px'
                }
              }),
              h('span', temp)
            ]
          ),
          h('span', {
            style: {
              display: 'inline-block',
              float: 'right',
              marginRight: '32px'
            }
          }, [
            h('Button', {
              props: Object.assign({}, this.buttonProps, {
                icon: 'ios-add'
              }),
              style: {
                marginRight: '8px'
              },
              on: {
                click: () => {
                  this.append(data)
                }
              }
            }),
            h('Button', {
              props: Object.assign({}, this.buttonProps, {
                icon: 'ios-remove'
              }),
              on: {
                click: () => {
                  this.remove(root, node, data)
                }
              }
            })
          ])
        ])
      },
      append (data) {
        this.currentData = data;
        this.modal11 = true;
      },
      remove (root, node, data) {
        const parentKey = root.find(el => el === node).parent;
        const parent = root.find(el => el.nodeKey === parentKey).node;
        const index = parent.children.indexOf(data);
        parent.children.splice(index, 1);
      },
      asyncOK () {
        let children = this.currentData.children || [];
        children.push({
          title: this.tempName,
          expand: true,
          selected: true,
          content: ''
        });
        this.$set(this.currentData, 'children', children);
        this.tempName = '';
      },
      handleCancel () {
        this.$router.push({ name: 'digitalProductsList' });
      },
      setChildrenData (dataChildren, parentObj) {
        if (dataChildren) {
          let children = this.currentData.children || [];
          for (let i = 0; i < dataChildren.length; i++) {
            let child = dataChildren[i];
            let obj = {
              title: child.title,
              expand: true,
              selected: true,
              content: child.content
            };
            children.push(obj);
            this.$set(parentObj, 'children', children);
            if (child.children) {
              this.setChildrenData(child.children, obj)
            }
          }
        }
      },
      getChildrenData (children, contentData) {
        if (children) {
          for (let i = 0; i < children.length; i++) {
            let child = children[i];
            let childData = {};
            childData.title = child.title;
            childData.content = child.content;
            contentData.push(childData);
            if (child.children) {
              childData.children = [];
              this.getChildrenData(child.children, childData.children)
            }
          }
        }
      },
      handleSave () {
        let saveData = {};
        let newData = this.treeData[0];
        let children = newData.children;
        let contentData = [];
        this.getChildrenData(children, contentData);
        saveData.name = newData.title;
        saveData.id = newData.id;
        saveData.remark = newData.content;
        saveData.content = JSON.stringify(contentData);
        this.post(this.api.digitalProducts.saveDigitalProducts, saveData).then((res) => {
          if (res.data.code === '200') {
            this.$router.push({ name: 'digitalProductsList' });
          }
        })
      }
    },
    computed: {
      ...mapGetters([
        'page'
      ])
    },
    components: {
      Page,
      VueNeditorWrap
    }
  }
</script>

<style>
  .demo-tree-render .ivu-tree-title {
    width: 100%;
  }

  .editor {
    position: static;
    margin-left: 0px;
    margin-right: 70px;
    margin-bottom: 20px;
    height: 700px;
  }

  .info .el-input {
    width: 90%;
  }

  .avatar-uploader .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 98px;
    height: 98px;
    line-height: 100px;
    text-align: center;
  }

  .editorForm {
    height: 650px;
  }
</style>
